package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.task.ArticleTasks;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.sun.org.apache.regexp.internal.RE;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-13
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    private ArticleTasks tasks;

    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {

        ApArticle apArticle = new ApArticle();

        BeanUtils.copyProperties(dto, apArticle);

        if (dto.getId() == null) {

            apArticle.setCreatedTime(new Date());

            this.save(apArticle);

            ApArticleContent apArticleContent = new ApArticleContent();

            apArticleContent.setArticleId(apArticle.getId());

            apArticleContent.setContent(dto.getContent());

            contentService.save(apArticleContent);

            tasks.createHtml(apArticle, dto.getContent());

            return ResponseResult.okResult(apArticle.getId());
        } else {

            this.updateById(apArticle);

            LambdaUpdateWrapper<ApArticleContent> update = new LambdaUpdateWrapper<>();

            update.eq(ApArticleContent::getId, dto.getId());

            update.set(ApArticleContent::getContent, dto.getContent());

            contentService.update(update);

            tasks.createHtml(apArticle, dto.getContent());

            return ResponseResult.okResult(apArticle.getId());
        }
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto, int type) {

        // 默认加载10篇文章
        if (dto.getSize() <= 0 || dto.getSize() > 50) {
            dto.setSize(10);
        }
        if (dto.getLoaddir() == 1) {

            String key = "hot_article_first_page_" + dto.getChannelId();
            long start = 0;
            long end = dto.getSize() - 1;

            Set<String> strings = redisTemplate.opsForZSet().reverseRange(key, start, end);

            List<ApArticle> list = new ArrayList<>();

            for (String string : strings) {

                ApArticle apArticle = JSON.parseObject(string, ApArticle.class);

                list.add(apArticle);
            }
            if (list.size() >= dto.getSize()) {

                return ResponseResult.okResult(list);
            }
        }
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();

        if (dto.getChannelId() != null && dto.getChannelId() != 0) {

            query.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        query.orderByDesc(ApArticle::getPublishTime);

        if (type == 1) {

            query.lt(ApArticle::getPublishTime, dto.getMinTime());
        } else {

            query.gt(ApArticle::getPublishTime, dto.getMaxTime());
        }
        query.eq(ApArticle::getIsDelete, false);
        query.eq(ApArticle::getIsDown, false);

        IPage<ApArticle> page = new Page<>();

        IPage<ApArticle> page1 = this.page(page, query);

        return ResponseResult.okResult(page1.getRecords());
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {

        System.out.println("文章的id是：" + dto.getArticleId());

        ApArticle byId = this.getById(dto.getArticleId());

        if (byId == null || byId.getIsDelete() || byId.getIsDown()) {

            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();

        query.eq(ApArticleContent::getArticleId, dto.getArticleId());

        ApArticleContent one = contentService.getOne(query);

        Map<String, Object> map = new HashMap<>();

        map.put("config", byId);

        map.put("content", one);

        return ResponseResult.okResult(map);
    }
}
